// ============================================================ //
// ============================================================ //
//
// @Group       : QiXin Supply Chain Team
// @Author      : ZhiQiang Cheng
// @Date        : 2024-07-15
// @Description : 团购房间DAO
//
// ============================================================ //
// ============================================================ //

package dao

import (
	"errors"
	"wooha-cache-hub/model"
	"wooha-cache-hub/utils"

	"github.com/StarfishProgram/starfish-go-sdk/sdkdb"
	"github.com/StarfishProgram/starfish-go-sdk/sdktypes"
	"gorm.io/gorm"
)

type groupBuyingRoom struct{}

var GroupBuyingRoom = new(groupBuyingRoom)

// ============================================================ //
// 通过ID获取房间信息
// ============================================================ //

func (gbr *groupBuyingRoom) GetById(id sdktypes.ID) (*model.GroupBuyingRoom, error) {
	var result model.GroupBuyingRoom
	sql := sdkdb.Ins().Table("group_buying_room gbr")
	sql.Where("gbr.id = ?", id)
	// 暂时不处理枚举: 1 = 已开奖, 4 = 已领取
	err := sql.Select(`
		gbr.*,
		(
			select gb.id from group_buying gb
			where gb.room_id = gbr.id and gb.status in (1, 4)
			order by gb.id desc
			limit 1
		) as prev_group_buying_id
	`).Take(&result).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, nil
		}
		return nil, err
	}
	return &result, nil
}

// ============================================================ //
// 查询团购最近5条投票
// ============================================================ //

func (gbr *groupBuyingRoom) GetVoteLast(groupBuyingId sdktypes.ID) ([]*model.GroupBuyingVoteDetail, error) {
	var list []*model.GroupBuyingVoteDetail
	sql := sdkdb.Ins().Table("group_buying_participate_statistics gbp")
	sql.Joins("left join users u on u.id = gbp.members_id")
	sql.Joins("left join group_buying gb on gb.id = gbp.group_buying_id")
	sql.Where("gbp.group_buying_id = ?", groupBuyingId)
	sql.Order("gbp.last_modified_date desc")
	sql.Select(`
		gbp.id,
		gbp.created_date,
		gbp.last_modified_date,
		gbp.group_buying_id,
		gbp.lottery_num_section,
		gbp.members_id,
		gbp.is_winner,
		u.username as members_name,
		u.avatar as members_avatar,
		gbp.current_tickets as tickets_amount,
		gb.winner_user_id,
		gb.winner_id,
		gb.sponsor_id
	`)
	if err := sql.Limit(5).Find(&list).Error; err != nil {
		return nil, err
	}

	for _, item := range list {
		item.MembersName = utils.DesensitizationUsername(item.MembersName)
	}
	return list, nil
}

// ============================================================ //
// 查询房间用户最近10条奖品
// ============================================================ //

func (gbr *groupBuyingRoom) GetUserPrize(
	roomId sdktypes.ID,
	userId sdktypes.ID,
) ([]*model.GroupBuyingPrizeInfo, error) {
	var result []*model.GroupBuyingPrizeInfo
	sql := sdkdb.Ins().Table("group_buying gb")
	sql.Joins("left join users u on u.id = gb.winner_user_id")
	sql.Joins("left join product p on p.id = gb.product_id")
	// 暂不处理枚举：1 = 已开奖
	sql.Where("gb.status = 1")
	sql.Where("gb.room_id = ?", roomId)
	sql.Where("gb.winner_user_id = ?", userId)
	sql.Order("gb.created_date desc")
	sql.Select(`
		gb.*,
		p.name as product_name,
		p.productImages as product_images,
		p.introduction as product_description,
		gb.id as group_buying_id,
		gb.winner_id as participate_id,
		u.username as members_name,
		u.avatar as members_avatar,
		(
			select 
				count(0) 
			from group_buying_auction gba 
			where 
				gba.group_buying_id = gb.id 
				and gba.is_frozen = 0
		) as pending_offers_quantity
	`)
	if err := sql.Limit(10).Find(&result).Error; err != nil {
		return nil, err
	}
	return result, nil
}
